const userModel = require('../models/userModel');
const { sendSuccess, sendError } = require('../utils/response');

module.exports = {
  // 获取用户信息
  async getUser(req, res) {
    try {
      const { id } = req.params;
      const user = await userModel.getUserById(id);
      sendSuccess(res, user);
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 更新用户信息
  async updateUser(req, res) {
    try {
      const { id } = req.user;
      const { username, email, phone } = req.body;
      
      const updated = await userModel.updateUser(id, { username, email, phone });
      
      if (!updated) {
        return sendError(res, '更新失败', 400);
      }
      
      const user = await userModel.getUserById(id);
      sendSuccess(res, user, '用户信息更新成功');
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 更新用户头像
  async updateAvatar(req, res) {
    try {
      const { id } = req.user;
      
      if (!req.file) {
        return sendError(res, '请上传头像', 400);
      }
      
      const avatarPath = `/public/uploads/${req.file.filename}`;
      const updated = await userModel.updateAvatar(id, avatarPath);
      
      if (!updated) {
        return sendError(res, '头像更新失败', 400);
      }
      
      const user = await userModel.getUserById(id);
      sendSuccess(res, user, '头像更新成功');
    } catch (err) {
      sendError(res, err.message);
    }
  }
  ,
  // 获取所有用户(管理员权限)
  async getAllUsers(req, res) {
    try {
      const { page = 1, limit = 10, keyword } = req.query;
      
      // 从模型获取用户数据
      const users = await userModel.getAllUsers({
        page: parseInt(page),
        limit: parseInt(limit),
        keyword
      });
      
      sendSuccess(res, users);
    } catch (err) {
      sendError(res, err.message);
    }
  },
};